<?php
/**
 * @author mwalters8@gmail.com
 * @version 1.0
 * @license Copyright (C) 2009  Matthew S. Walters
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 **/

/*
========================================================
Execute the below SQL statement to setup the user table.
========================================================

SET FOREIGN_KEY_CHECKS = 0;

CREATE TABLE `userGroupKey` (
  `id` int(10) NOT NULL auto_increment,
  `creation_date` timestamp NOT NULL default '0000-00-00 00:00:00',
  `modification_date` timestamp NOT NULL default '0000-00-00 00:00:00' on update CURRENT_TIMESTAMP,
  `users_id` int(10) NOT NULL default '0',
  `userGroups_id` int(10) NOT NULL default '0',
  `status` enum('Active','Inactive','Delete') NOT NULL default 'Active',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=432 DEFAULT CHARSET=utf8;


CREATE TABLE `userGroups` (
  `id` int(10) NOT NULL auto_increment,
  `creation_date` timestamp NOT NULL default '0000-00-00 00:00:00',
  `modification_date` timestamp NOT NULL default '0000-00-00 00:00:00' on update CURRENT_TIMESTAMP,
  `groupName` varchar(255) NOT NULL default '',
  `status` enum('Active','Inactive','Delete') NOT NULL default 'Active',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=86 DEFAULT CHARSET=utf8;


CREATE TABLE `users` (
  `id` int(10) NOT NULL auto_increment,
  `creation_date` timestamp NOT NULL default '0000-00-00 00:00:00',
  `modification_date` timestamp NOT NULL default '0000-00-00 00:00:00' on update CURRENT_TIMESTAMP,
  `username` varchar(255) NOT NULL default '',
  `password` varchar(255) NOT NULL default '',
  `status` enum('Active','Inactive','Delete') NOT NULL default 'Active',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=57 DEFAULT CHARSET=utf8;


SET FOREIGN_KEY_CHECKS = 1;

*/

// Configure for your database
define('DB_SERVER', 'localhost'); // Server IP Address
define('DB_NAME', 'users'); // Name of database
define('DB_USER', 'users'); // Database Username
define('DB_PASSWORD', 'users'); // Database Password

class User {
	function __construct($userId) {
		$this->load($userId);
		return;
	}
	
	function __destruct() {
		return;
	}

	protected function query($sql) {
		// Connect to the MySQL Server
		$dbLink = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
		If (!$dbLink) { // Could not connect to database server, return an error
			$queryResults['Error_Code'] = 101;
			$queryResults['Error_Message'] = 'Unable to connect to database server.';
			return($queryResults);
		}

		// Select the database
		$dbSelected = mysql_select_db(DB_NAME, $dbLink);
		If (!$dbSelected) { // Could not select database, return an error
			$queryResults['Error_Code'] = 102;
			$queryResults['Error_Message'] = 'Could not select database: ' . mysql_error();
			return($queryResults);
		}

		// Perform the query
		$queryResponse = mysql_query($sql);

		If (!$queryResponse) { // Could not perform query, return an error
			$queryResults['Error_Code'] = 103;
			$queryResults['Error_Message'] = 'Query Error: ' . mysql_error();
			return($queryResults);
		}

		If (substr($sql, 0, 6) == 'SELECT') {
			// Loop through results and add the recordset to Results_Array
			$recordCount = 1;
			while ($row = mysql_fetch_assoc($queryResponse)) {
				foreach ($row as $fieldName => $fieldValue) {
					$queryResults['Recordset'][$recordCount][$fieldName] = $fieldValue;
				}
				$recordCount++;
			}
			mysql_free_result($queryResponse);
		}

		// If it was an INSERT statement, then get the new Primary Key to return it
		If (substr($sql, 0, 6) == 'INSERT') {
			$queryResults['Inserted_ID'] = mysql_insert_id();
		}

		// If it was an UPDATE or DELETE statement, then get the number of rows that were affected to return it
		If (substr($sql, 0, 6) == 'UPDATE' || substr($sql, 0, 6) == 'DELETE') {
			$queryResults['Affected_Rows'] = mysql_affected_rows();
		}

		$queryResults['Error_Code'] = 0; // If we got to here, then there aren't any errors, so set error code to 0 and return the results
		$queryResults['Error_Message'] = '';
		mysql_close($dbLink);
		return($queryResults);
		return;
	}

	protected function prepare($string) {
		$dbLink = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) OR die(mysql_error());
		$string = mysql_real_escape_string($string);

		return('"' . $string . '"');
	}

	protected function timestamp() {
		return(date('Y-m-d H:i:s', time()));
	}

	public function load($userId) {
		$sql = 'SELECT * FROM users WHERE (id=' . $this->prepare($userId) . ') LIMIT 0,1;';
		$userData = $this->query($sql);
		if (count($userData['Recordset']) == 1) {
			foreach ($userData['Recordset'][1] as $field=>$value) {
				$this->$field = $value;
			}
		}
		return;
	}

	public function save() {
		$sql = 'UPDATE users SET ';
		foreach ($this as $field=>$value) {
			if ($field != 'id') { $sql .= $field . '=' . $this->prepare($value) . ', '; }
		}
		$sql = substr($sql, 0, (strlen($sql) - 2));
		$sql .= ' WHERE (id='.$this->id.');';
		$this->query($sql);
		return;
	}

	public function delete() {
		$sql = 'DELETE FROM users WHERE (id=' . $this->prepare($this->id) . ');';
		$this->query($sql);
		return;
	}

	protected function addGroup($groupName) {
		return;
	}

	protected function removeGroup($groupName) {
		return;
	}

	protected function getGroups() {
		return;
	}

	protected function isMemberOf($groupName) {
		return;
	}
}

?>